package net.work.download;

import net.upload.StreamUtils;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 文件下载 --- 客户端的代码
 */
public class Work03Client {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入下载文件名");
        String downloadFileName = sc.next();

        Socket socket = new Socket("127.0.0.1", 9999);
        // 3, 获取 socket 相关的输出流
        OutputStream os = socket.getOutputStream();
        // 写入文件名
        os.write(downloadFileName.getBytes());
        // 写入结束标记
        socket.shutdownOutput();
        //4. 读取服务端返回的文件 （字节数组）
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        byte[] buffer = StreamUtils.streamToByteArray(bis);
        // 5. 得到一个输出流 将文件写入磁盘 === 注意自己加后缀
        String filePath = "f:\\" + downloadFileName + ".jpg";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        bos.write(buffer);
        // 关闭相关资源
        bos.close();
        bis.close();
        os.close();
        socket.close();
        System.out.println("客户端下载完毕。。。。");

    }
}
